/**
 * 观点面板组件
 * 管理多AI观点生成、展示和选择
 */

import React, { useState, useEffect } from 'react';
import {
  Card,
  Button,
  Space,
  Select,
  Checkbox,
  Row,
  Col,
  Modal,
  message,
  Spin,
  Empty,
  Tabs,
  Statistic,
} from 'antd';
import {
  ThunderboltOutlined,
  ReloadOutlined,
  EyeOutlined,
  EditOutlined,
  CheckOutlined,
} from '@ant-design/icons';
import { useBrainstormStore } from '@/stores/brainstorm.store';
import { multiAIViewpointService } from '@/services/multi-ai-viewpoint.service';
import userModelsService from '@/services/user-models.service';
import type { UserModel } from '@/services/user-models.service';
import { ViewpointCard } from '../ViewpointCard';
import { Viewpoint, PerspectiveType } from '@/types/brainstorm';
import './style.css';

const { Option } = Select;

interface ViewpointPanelProps {
  onContinue?: () => void;
}

export const ViewpointPanel: React.FC<ViewpointPanelProps> = ({ onContinue }) => {
  const { currentSession, updateSession } = useBrainstormStore();
  const [availableModels, setAvailableModels] = useState<UserModel[]>([]);
  const [loadingModels, setLoadingModels] = useState(true);
  const [selectedModels, setSelectedModels] = useState<string[]>([]);
  const [selectedViewpoints, setSelectedViewpoints] = useState<string[]>([]);
  const [generating, setGenerating] = useState(false);
  const [editingViewpoint, setEditingViewpoint] = useState<Viewpoint | null>(null);
  const [showMindMap, setShowMindMap] = useState(false);

  const viewpoints = currentSession?.viewpoints || [];

  // 加载可用模型
  useEffect(() => {
    const loadModels = async () => {
      setLoadingModels(true);
      try {
        const models = await userModelsService.getAvailableModels();
        // 只筛选已启用且健康的模型
        const enabledModels = models.filter(m => m.enabled && m.status === 'healthy');
        setAvailableModels(enabledModels);

        console.log(`筛选后可用模型: ${enabledModels.length} 个`, enabledModels.map(m => ({
          name: m.displayName,
          status: m.status,
          enabled: m.enabled
        })));

        // 默认选中前2个模型
        if (enabledModels.length > 0) {
          const defaultSelected = enabledModels.slice(0, Math.min(2, enabledModels.length)).map(m => m.id);
          setSelectedModels(defaultSelected);
        }
      } catch (error) {
        console.error('加载模型列表失败:', error);
        message.error('加载模型列表失败');
      } finally {
        setLoadingModels(false);
      }
    };

    loadModels();
  }, []);

  // 统计数据
  const stats = {
    total: viewpoints.length,
    generating: viewpoints.filter((v) => v.generating).length,
    completed: viewpoints.filter((v) => v.completed).length,
    failed: viewpoints.filter((v) => v.error).length,
    selected: selectedViewpoints.length,
  };

  // 生成所有观点
  const handleGenerateAll = async () => {
    console.log('🔵 [ViewpointPanel] handleGenerateAll 被调用');
    console.log('🔵 [ViewpointPanel] currentSession:', currentSession);
    console.log('🔵 [ViewpointPanel] selectedModels:', selectedModels);
    console.log('🔵 [ViewpointPanel] generating:', generating);
    console.log('🔵 [ViewpointPanel] stats.generating:', stats.generating);

    if (!currentSession) {
      console.error('❌ 当前没有活跃会话');
      message.error('当前没有活跃会话');
      return;
    }

    if (selectedModels.length === 0) {
      console.warn('⚠️ 没有选择AI模型');
      message.warning('请至少选择一个AI模型');
      return;
    }

    console.log('✅ 开始生成观点...');
    setGenerating(true);
    try {
      await multiAIViewpointService.generateAllPerspectives(
        currentSession.id,
        selectedModels
      );
      message.success(`已启动 ${selectedModels.length} 个AI模型生成观点`);
    } catch (error) {
      console.error('❌ 生成观点失败:', error);
      message.error('生成观点失败，请稍后重试');
    } finally {
      setGenerating(false);
    }
  };

  // 重新生成单个观点
  const handleRegenerateViewpoint = async (viewpointId: string) => {
    try {
      await multiAIViewpointService.regenerateViewpoint(viewpointId);
      message.success('已重新生成观点');
    } catch (error) {
      console.error('重新生成失败:', error);
      message.error('重新生成失败');
    }
  };

  // 选择/取消选择观点
  const handleSelectViewpoint = (viewpointId: string) => {
    setSelectedViewpoints((prev) =>
      prev.includes(viewpointId)
        ? prev.filter((id) => id !== viewpointId)
        : [...prev, viewpointId]
    );
  };

  // 编辑观点
  const handleEditViewpoint = (viewpoint: Viewpoint) => {
    setEditingViewpoint(viewpoint);
  };

  // 用户评分
  const handleRateViewpoint = (viewpointId: string, rating: number) => {
    console.log(`用户给观点 ${viewpointId} 评分:`, rating);
    // TODO: 保存用户评分到后端
  };

  // 继续到下一步
  const handleContinue = () => {
    if (selectedViewpoints.length === 0) {
      message.warning('请至少选择一个观点');
      return;
    }

    message.success(`已选择 ${selectedViewpoints.length} 个观点`);
    onContinue?.();
  };

  // 渲染统计卡片
  const renderStatsCard = () => (
    <Card className="stats-card" bordered={false}>
      <Row gutter={[16, 16]}>
        <Col span={6}>
          <Statistic title="总观点数" value={stats.total} />
        </Col>
        <Col span={6}>
          <Statistic
            title="生成中"
            value={stats.generating}
            valueStyle={{ color: '#1890ff' }}
            prefix={<ThunderboltOutlined spin />}
          />
        </Col>
        <Col span={6}>
          <Statistic
            title="已完成"
            value={stats.completed}
            valueStyle={{ color: '#52c41a' }}
            prefix={<CheckOutlined />}
          />
        </Col>
        <Col span={6}>
          <Statistic
            title="已选择"
            value={stats.selected}
            valueStyle={{ color: '#722ed1' }}
          />
        </Col>
      </Row>
    </Card>
  );

  // 渲染控制面板
  const renderControlPanel = () => (
    <Card className="control-panel" title="生成控制" bordered={false}>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        {/* 模型选择 */}
        <div className="control-item">
          <label className="control-label">选择AI模型（多选）:</label>
          {loadingModels ? (
            <Spin tip="加载模型列表中..." />
          ) : availableModels.length === 0 ? (
            <Empty
              description="暂无可用模型"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            >
              <Button type="link" onClick={() => window.open('/settings/model-config', '_blank')}>
                去配置模型
              </Button>
            </Empty>
          ) : (
            <Checkbox.Group
              value={selectedModels}
              onChange={(values) => setSelectedModels(values as string[])}
              style={{ width: '100%' }}
            >
              <Row gutter={[8, 8]}>
                {availableModels.map((model) => (
                  <Col key={model.id} span={12}>
                    <Checkbox value={model.id}>
                      <div>
                        <div style={{ fontWeight: 500 }}>{model.displayName}</div>
                        <div style={{ fontSize: '12px', color: '#8c8c8c' }}>
                          {model.providerName} / {model.modelName}
                        </div>
                      </div>
                    </Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
          )}
        </div>

        {/* 操作按钮 */}
        <Space>
          <Button
            type="primary"
            icon={<ThunderboltOutlined />}
            onClick={handleGenerateAll}
            loading={generating}
            disabled={selectedModels.length === 0 || stats.generating > 0 || loadingModels}
          >
            生成所有观点
          </Button>
          <Button
            icon={<ReloadOutlined />}
            onClick={() => {
              // 重新生成所有失败的观点
              viewpoints
                .filter((v) => v.error)
                .forEach((v) => handleRegenerateViewpoint(v.id));
            }}
            disabled={stats.failed === 0}
          >
            重试失败项 ({stats.failed})
          </Button>
          <Button
            icon={<EyeOutlined />}
            onClick={() => setShowMindMap(true)}
            disabled={stats.completed === 0}
          >
            查看思维导图
          </Button>
        </Space>
      </Space>
    </Card>
  );

  // 渲染观点列表
  const renderViewpointGrid = () => {
    if (viewpoints.length === 0) {
      return (
        <Card>
          <Empty
            description={
              <div>
                <p>还没有生成观点</p>
                <p style={{ fontSize: '12px', color: '#8c8c8c' }}>
                  选择AI模型后，点击"生成所有观点"开始
                </p>
              </div>
            }
          />
        </Card>
      );
    }

    // 按视角分组
    const groupedByPerspective: Record<PerspectiveType, Viewpoint[]> = {
      rational: [],
      emotional: [],
      innovative: [],
      popular: [],
    };

    viewpoints.forEach((v) => {
      groupedByPerspective[v.perspective].push(v);
    });

    const perspectiveNames: Record<PerspectiveType, string> = {
      rational: '理性分析',
      emotional: '情感共鸣',
      innovative: '创新思维',
      popular: '大众实用',
    };

    return (
      <Tabs defaultActiveKey="all" className="viewpoint-tabs">
        <Tabs.TabPane tab="全部观点" key="all">
          <Row gutter={[16, 16]}>
            {viewpoints.map((viewpoint) => (
              <Col key={viewpoint.id} xs={24} sm={24} md={12} lg={12} xl={12}>
                <ViewpointCard
                  viewpoint={viewpoint}
                  selected={selectedViewpoints.includes(viewpoint.id)}
                  onSelect={handleSelectViewpoint}
                  onEdit={handleEditViewpoint}
                  onRegenerate={handleRegenerateViewpoint}
                  onRate={handleRateViewpoint}
                />
              </Col>
            ))}
          </Row>
        </Tabs.TabPane>

        {/* 按视角分类 */}
        {Object.entries(groupedByPerspective).map(([perspective, vpList]) => {
          if (vpList.length === 0) return null;
          return (
            <Tabs.TabPane
              tab={`${perspectiveNames[perspective as PerspectiveType]} (${vpList.length})`}
              key={perspective}
            >
              <Row gutter={[16, 16]}>
                {vpList.map((viewpoint) => (
                  <Col key={viewpoint.id} xs={24} sm={24} md={12} lg={12} xl={12}>
                    <ViewpointCard
                      viewpoint={viewpoint}
                      selected={selectedViewpoints.includes(viewpoint.id)}
                      onSelect={handleSelectViewpoint}
                      onEdit={handleEditViewpoint}
                      onRegenerate={handleRegenerateViewpoint}
                      onRate={handleRateViewpoint}
                    />
                  </Col>
                ))}
              </Row>
            </Tabs.TabPane>
          );
        })}
      </Tabs>
    );
  };

  return (
    <div className="viewpoint-panel">
      <div className="panel-header">
        <h2>🧠 多AI观点建议</h2>
        <p className="panel-subtitle">
          让不同AI模型从多个视角提供创作灵感，选择最适合的观点继续创作
        </p>
      </div>

      {/* 统计信息 */}
      {renderStatsCard()}

      {/* 控制面板 */}
      {renderControlPanel()}

      {/* 观点列表 */}
      {renderViewpointGrid()}

      {/* 底部操作 */}
      <div className="panel-footer">
        <Space>
          <Button size="large" onClick={() => window.history.back()}>
            返回问答
          </Button>
          <Button
            type="primary"
            size="large"
            onClick={handleContinue}
            disabled={selectedViewpoints.length === 0}
          >
            继续（已选择 {selectedViewpoints.length} 个观点）
          </Button>
        </Space>
      </div>

      {/* 编辑观点模态框 */}
      <Modal
        title="编辑观点"
        open={!!editingViewpoint}
        onCancel={() => setEditingViewpoint(null)}
        onOk={() => {
          // TODO: 保存编辑后的观点
          message.success('观点已保存');
          setEditingViewpoint(null);
        }}
        width={800}
      >
        {/* TODO: 实现观点编辑表单 */}
        <p>观点编辑功能待实现</p>
      </Modal>
    </div>
  );
};
